/**
 * 用户喜欢模块
 * 管理用户喜欢的图案
 */
const {
	userFavouriteCollection,
	patternCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')
const {
	getUserId
} = require('../../common/utils')

module.exports = {
	/**
	 * 获取用户喜欢的图案列表
	 * @param {object} params 查询参数
	 * @param {number} [params.page=1] 页码
	 * @param {number} [params.limit=20] 每页数量
	 * @returns {object} 喜欢的图案列表
	 */
	async getUserFavourites(params = {}) {
		try {
			const userId = await getUserId(this)
			const { page = 1, limit = 20 } = params
			
			// 获取用户喜欢记录
			const favouriteResult = await userFavouriteCollection.where({
				user_id: userId
			}).get()

			// 如果没有记录，初始化一个空记录
			if (favouriteResult.data.length === 0) {
				await this.initUserFavourites()
				return {
					errCode: 0,
					errMsg: this.t ? this.t('favourite.get.success') : '获取成功',
					data: {
						patterns: [],
						total: 0,
						page,
						limit,
						pages: 0
					}
				}
			}

			const favourite = favouriteResult.data[0]
			const patterns = favourite.patterns || []

			// 计算分页
			const total = patterns.length
			const pages = Math.ceil(total / limit)
			const startIndex = (page - 1) * limit
			const endIndex = startIndex + limit
			const paginatedPatterns = patterns.slice(startIndex, endIndex)

			// 如果有图案，获取完整的图案信息
			let detailedPatterns = []
			if (paginatedPatterns.length > 0) {
				const patternIds = paginatedPatterns.map(p => p.pattern_id)
				const patternResult = await patternCollection.where({
					_id: dbCmd.in(patternIds),
					status: 1 // 只获取已发布的图案
				}).get()

				// 获取当前请求的语言
				const language = this.language || 'zh-Hans'

				// 转换图案数据格式
				const transformedPatterns = transformMultiLangData(patternResult.data, language, {
					multiLangFields: ['pattern_name', 'description'],
					keepFields: [
						'pattern_file', 'preview_image', 'category', 'tags', 'duration', 'play_time',
						'difficulty', 'download_count', 'favorite_count', 'designer',
						'is_featured', 'is_premium', 'compatible_devices', 'create_time'
					],
					idMapping: { '_id': 'pattern_id' }
				})

				// 按照喜欢列表的排序合并数据
				detailedPatterns = paginatedPatterns.map(favPattern => {
					const patternDetail = transformedPatterns.find(p => p.pattern_id === favPattern.pattern_id)
					if (patternDetail) {
						return {
							...patternDetail,
							sort_order: favPattern.sort_order,
							add_time: favPattern.add_time
						}
					}
					return null
				}).filter(Boolean)
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('favourite.get.success') : '获取成功',
				data: {
					patterns: detailedPatterns,
					total,
					page,
					limit,
					pages
				}
			}
		} catch (error) {
			console.error('[sh_user_favourite] getUserFavourites error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.get.failed') : '获取喜欢列表失败'
			}
		}
	},

	/**
	 * 添加图案到喜欢列表
	 * @param {object} params 添加参数
	 * @param {string} params.pattern_id 图案ID
	 * @returns {object} 添加结果
	 */
	async addPatternToFavourites(params) {
		const { pattern_id } = params

		if (!pattern_id) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'pattern_id' }
			}
		}

		try {
			const userId = await getUserId(this)

			// 检查图案是否存在
			const patternResult = await patternCollection.where({
				_id: pattern_id,
				status: 1
			}).get()

			if (patternResult.data.length === 0) {
				throw {
					errCode: ERROR.PATTERN_NOT_FOUND
				}
			}

			// 获取用户喜欢记录
			const favouriteResult = await userFavouriteCollection.where({
				user_id: userId
			}).get()

			let favourite
			if (favouriteResult.data.length === 0) {
				// 初始化用户喜欢记录
				favourite = await this.initUserFavourites()
			} else {
				favourite = favouriteResult.data[0]
			}

			// 检查图案是否已经在喜欢列表中
			const existingPattern = favourite.patterns.find(p => p.pattern_id === pattern_id)
			if (existingPattern) {
				throw {
					errCode: ERROR.PATTERN_ALREADY_IN_FAVOURITE
				}
			}

			// 计算新的排序顺序（添加到最前面）
			const maxSortOrder = favourite.patterns.length > 0 
				? Math.max(...favourite.patterns.map(p => p.sort_order)) 
				: 0
			const newSortOrder = maxSortOrder + 1

			// 添加图案到喜欢列表
			const updateResult = await userFavouriteCollection.doc(favourite._id).update({
				patterns: dbCmd.push({
					pattern_id,
					sort_order: newSortOrder,
					add_time: new Date()
				}),
				pattern_count: dbCmd.inc(1),
				update_time: new Date()
			})

			if (updateResult.updated === 0) {
				throw {
					errCode: ERROR.UPDATE_FAILED
				}
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('favourite.add.success') : '添加成功',
				data: {
					pattern_id,
					sort_order: newSortOrder
				}
			}
		} catch (error) {
			console.error('[sh_user_favourite] addPatternToFavourites error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.add.failed') : '添加到喜欢列表失败'
			}
		}
	},

	/**
	 * 从喜欢列表移除图案
	 * @param {object} params 移除参数
	 * @param {string} params.pattern_id 图案ID
	 * @returns {object} 移除结果
	 */
	async removePatternFromFavourites(params) {
		const { pattern_id } = params

		if (!pattern_id) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'pattern_id' }
			}
		}

		try {
			const userId = await getUserId(this)

			// 获取用户喜欢记录
			const favouriteResult = await userFavouriteCollection.where({
				user_id: userId
			}).get()

			if (favouriteResult.data.length === 0) {
				throw {
					errCode: ERROR.FAVOURITE_NOT_FOUND
				}
			}

			const favourite = favouriteResult.data[0]

			// 检查图案是否在喜欢列表中
			const patternIndex = favourite.patterns.findIndex(p => p.pattern_id === pattern_id)
			if (patternIndex === -1) {
				throw {
					errCode: ERROR.PATTERN_NOT_IN_FAVOURITE
				}
			}

			// 移除图案
			const updatedPatterns = favourite.patterns.filter(p => p.pattern_id !== pattern_id)

			const updateResult = await userFavouriteCollection.doc(favourite._id).update({
				patterns: updatedPatterns,
				pattern_count: updatedPatterns.length,
				update_time: new Date()
			})

			if (updateResult.updated === 0) {
				throw {
					errCode: ERROR.UPDATE_FAILED
				}
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('favourite.remove.success') : '移除成功',
				data: {
					pattern_id,
					removed: true
				}
			}
		} catch (error) {
			console.error('[sh_user_favourite] removePatternFromFavourites error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.remove.failed') : '从喜欢列表移除失败'
			}
		}
	},

	/**
	 * 检查图案是否在用户喜欢列表中
	 * @param {object} params 检查参数
	 * @param {string} params.pattern_id 图案ID
	 * @returns {object} 检查结果
	 */
	async checkPatternInFavourites(params) {
		const { pattern_id } = params

		if (!pattern_id) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'pattern_id' }
			}
		}

		try {
			const userId = await getUserId(this)

			// 获取用户喜欢记录
			const favouriteResult = await userFavouriteCollection.where({
				user_id: userId
			}).get()

			let isFavourite = false
			if (favouriteResult.data.length > 0) {
				const favourite = favouriteResult.data[0]
				isFavourite = favourite.patterns.some(p => p.pattern_id === pattern_id)
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('favourite.check.success') : '检查成功',
				data: {
					pattern_id,
					is_favourite: isFavourite
				}
			}
		} catch (error) {
			console.error('[sh_user_favourite] checkPatternInFavourites error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.check.failed') : '检查失败'
			}
		}
	},

	/**
	 * 初始化用户喜欢记录
	 * @returns {object} 初始化的记录
	 */
	async initUserFavourites() {
		try {
			const userId = await getUserId(this)

			const favouriteData = {
				user_id: userId,
				patterns: [],
				pattern_count: 0,
				create_time: new Date(),
				update_time: new Date()
			}

			const result = await userFavouriteCollection.add(favouriteData)

			return {
				_id: result.id,
				...favouriteData
			}
		} catch (error) {
			console.error('[sh_user_favourite] initUserFavourites error:', error)
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.init.failed') : '初始化喜欢列表失败'
			}
		}
	},

	/**
	 * 清空用户喜欢列表
	 * @returns {object} 清空结果
	 */
	async clearUserFavourites() {
		try {
			const userId = await getUserId(this)

			// 获取用户喜欢记录
			const favouriteResult = await userFavouriteCollection.where({
				user_id: userId
			}).get()

			if (favouriteResult.data.length === 0) {
				throw {
					errCode: ERROR.FAVOURITE_NOT_FOUND
				}
			}

			const favourite = favouriteResult.data[0]

			const updateResult = await userFavouriteCollection.doc(favourite._id).update({
				patterns: [],
				pattern_count: 0,
				update_time: new Date()
			})

			if (updateResult.updated === 0) {
				throw {
					errCode: ERROR.UPDATE_FAILED
				}
			}

			return {
				errCode: 0,
				errMsg: this.t ? this.t('favourite.clear.success') : '清空成功',
				data: {
					cleared: true
				}
			}
		} catch (error) {
			console.error('[sh_user_favourite] clearUserFavourites error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('favourite.clear.failed') : '清空喜欢列表失败'
			}
		}
	}
}
